<?php
namespace app\services;

use Fate;
use fate\http\Request;
use app\libs\mail\Mail;
use app\models\MailCode;

class MailService {

    public $msg = '';
    public $html = <<<STR
<div style="width:600px; background-color: #fff; margin:0 auto; border: 1px solid #ccc; border-radius: 10px;">
    <div style="padding: 20px; font-size: 22px; border-bottom: 1px solid #ccc;">[title]</div>
    <div style="padding: 20px">[content]</div>
    <div style="padding: 10px 20px; color: #999; font-size: 12px; border-top: 1px dashed #999;">本邮件由系统自动发送。</div>
</div>
STR;

    private function productCode($len = 4) {
        $code = '0123456789abcdefghijklmnopqrstuvwxyz';
        $chars = '';

        for($i=0; $i<$len; $i++) {
            $chars .= substr($code, mt_rand(0, strlen($code) - 1), 1);
        }

        return $chars;
    }

    /**
     * 发送注册验证码 5 min
     */
    public function sendRegisterCode($email, $life = 300) {
        $ini = Fate::$app->iniReader;
        $model = new MailCode();
        $code = $this->productCode();

        // 内容
        $html = $this->html;
        $title = $ini->get('seo', 'title');
        $content = '<p>尊敬的 '. $email .' ，您好：您正在注册本站会员，验证码如下：</p>'
            . '<p style="color: #008000; font-size: 32px">'. $code .'</p>';
        $html = str_replace('[title]', $title, $html);
        $html = str_replace('[content]', $content, $html);

        // 发送
        $mail = new Mail(Fate::$app->mail);
        $ret = $mail->sendMail($email, '【'. $title .'】注册通知', $html);

        // 保存数据库
        $model->insert([
            'code_type' => 1,
            'code' => $code,
            'email' => $email,
            'ip' => (Request::getInstance())->getUserIP(),
            'post_time' => time()
        ]);

        if(!$ret) {
            $this->msg = $mail->getMsg();

            return false;
        }

        return true;
    }

    public function validateRegisterCode($email, $code) {
        if(empty($code)) {
            return false;
        }

        $model = new MailCode();
        $ret = $model->getOneByCondition('id, code, email, is_used, post_time', "code_type=1 and email='{$email}'", 'id desc');

        // 没找到或者已经使用
        if(null === $ret || '1' === $ret['is_used']) {
            return false;
        }

        if($email === $ret['email'] && $code === $ret['code']) {
            $model->update($ret['id'], ['is_used' => 1]);
            return true;
        }

        return false;
    }

    /**
     * 发送找回密码验证码
     */
    public function sendFindCode($email, $life = 300) {
        $ini = Fate::$app->iniReader;
        $model = new MailCode();
        $code = $this->productCode();

        // 内容
        $html = $this->html;
        $title = $ini->get('seo', 'title');
        $content = '<p>尊敬的 '. $email .' ，您好：您正在找回密码，验证码如下：</p>'
            . '<p style="color: #008000; font-size: 32px">'. $code .'</p>';
        $html = str_replace('[title]', $title, $html);
        $html = str_replace('[content]', $content, $html);

        // 发送
        $mail = new Mail(Fate::$app->mail);
        $ret = $mail->sendMail($email, '【'. $title .'】找回密码通知', $html);

        // 保存数据库
        $model->insert([
            'code_type' => 2,
            'code' => $code,
            'email' => $email,
            'ip' => (Request::getInstance())->getUserIP(),
            'post_time' => time()
        ]);

        if(!$ret) {
            $this->msg = $mail->getMsg();

            return false;
        }

        return true;
    }

    public function validateFindCode($email, $code) {
        if(empty($code)) {
            return false;
        }

        $model = new MailCode();
        $ret = $model->getOneByCondition('id, code, email, is_used, post_time', "code_type=2 and email='{$email}'", 'id desc');

        // 没找到或者已经使用
        if(null === $ret || '1' === $ret['is_used']) {
            return false;
        }

        if($email === $ret['email'] && $code === $ret['code']) {
            $model->update($ret['id'], ['is_used' => 1]);
            return true;
        }

        return false;
    }

}
